﻿using AutoMapper;
using B.S.BasicData.Api.Write.Application.Command.User;
using B.S.BasicData.Domian.Entitys;
using B.S.BasicData.ErrorCode;
using B.S.BasicData.Infastructure.Interface;
using MediatR;
using Microsoft.EntityFrameworkCore;
using Yitter.IdGenerator;

namespace B.S.BasicData.Api.Write.Application.Handler.User
{
    public class CreateUserHandler : IRequestHandler<CreateUserCommand, ApiResult<int>>
    {
        private readonly IMapper _mapper;
        private readonly IBaseRepository<UsersModel> _userRepository;
        public CreateUserHandler(IMapper mapper, IBaseRepository<UsersModel> userRepository)
        {
            _mapper = mapper;
            _userRepository = userRepository;
        }

        /// <summary>
        /// 用户新增
        /// </summary>
        /// <param name="request">请求参数</param>
        /// <param name="cancellationToken">取消</param>
        /// <returns>返回受影响行数</returns>
        /// <exception cref="NotImplementedException"></exception>
        public Task<ApiResult<int>> Handle(CreateUserCommand request, CancellationToken cancellationToken)
        {
            ApiResult<int> result = new ApiResult<int>();
            var user = _userRepository.GetAll().FirstOrDefault(p => p.UserName == request.UserName);
            if (user != null)
            {
                result.Code = StatusEnum.Error;
                result.Message = "用户名重复";
                return Task.FromResult(result);
            }
            var model = _mapper.Map<UsersModel>(request);
            model.UserPwd = "12345678";
            model.CreateTime=DateTime.Now;
            model.Creater = "张三";
            model.UpdateTime=null;

            var res = _userRepository.Add(model);
            if(res>0)
            {
                result.Code =StatusEnum.OK;
                result.Data = res;
                result.Message = "添加成功";
            }
            else
            {
                result.Code =StatusEnum.Fail;
                result.Data = res;
                result.Message = "添加失败";
            }
            return Task.FromResult(result);
        }


    }
}
